package com.jy.wms.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.joyi.gate.comm.SessionInfo;
import com.joyi.gate.safety.vo.UserInfo;
import com.jy.wms.common.UUIDUtils;
import com.jy.wms.common.annotions.BaseServiceDescribe;
import com.jy.wms.common.base.*;
import com.jy.wms.dao.WmsPdaMsgMapper;
import com.jy.wms.dao.WmsPdaQuickMapper;
import com.jy.wms.dao.WmsQuickExitDetailedMapper;
import com.jy.wms.dao.WmsQuickExitMapper;
import com.jy.wms.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
    * @ClassName: WmsQuickExitService.java
    * @Description: TODO(这里用一句话描述这个类的作用)
    * @Author Liyi
    * @Date Sat Apr 28 09:08:37 CST 2018
    */

    @Service
    public class WmsQuickExitService extends BaseService<WmsQuickExitMapper,WmsQuickExit> {
        @Autowired
        private WmsQuickExitDetailedMapper wmsQuickExitDetailedMapper;
        @Autowired
        private WmsPdaQuickMapper wmsPdaQuickMapper;
        @Autowired
        private WmsPdaMsgMapper wmsPdaMsgMapper;

    /**
     * 获取快速出库发运编号
     * @return int
     */
    @BaseServiceDescribe(moduleName = "快速出库", btnName = "下发捡货任务")
    @Transactional
    public void getXf(String id,String ryid, HttpSession session)throws ServiceException,SucessException,Exception{
        //判断是否可以执行下发捡货任务
        WmsQuickExit wmsQuickExit = dao.baseSelectByPrimaryKey(id);
        if(!(wmsQuickExit.getFyzt().equals("0"))){
            throw new ServiceException("此订单已下发请勿重复操作！");
        }
        //获取明细列表
        List<Map<String,Object>> list = wmsQuickExitDetailedMapper.getList(id);
        StringBuffer message = new StringBuffer();
        for (Map<String, Object> stringObjectMap : list) {
            //如果可下架数量 小于 下发捡货任务数量则不允许下发
            if(wmsQuickExitDetailedMapper.getKykcsl(String.valueOf(stringObjectMap.get("kcid"))) <  Integer.valueOf(stringObjectMap.get("sl").toString())){
                message.append("货品名称：" + stringObjectMap.get("hpmc").toString() + " 库位名称："+ stringObjectMap.get("kwmc").toString() + ",");
            }
        }
        if(message.length() > 0){
            throw new ServiceException(message.toString() + "库存不足，扣减失败");
        }
        //增加带下架数量  生成 PDA捡货任务下发
        UserInfo userinfo = (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
        WmsPdaQuick wmsPdaQuick = new WmsPdaQuick();


        for (Map<String, Object> stringObjectMap : list) {
            wmsQuickExitDetailedMapper.addDxjsl(stringObjectMap.get("sl").toString(),String.valueOf(stringObjectMap.get("kcid")));
            wmsPdaQuick.setId(UUIDUtils.uuid());
            wmsPdaQuick.setKcdh(wmsQuickExit.getFybh());
            wmsPdaQuick.setGg(stringObjectMap.get("gg").toString());
            wmsPdaQuick.setHpbh(stringObjectMap.get("hpbh").toString());
            wmsPdaQuick.setHpmc(stringObjectMap.get("hpmc").toString());
            wmsPdaQuick.setHppc(stringObjectMap.get("hppc").toString());
            wmsPdaQuick.setHsl(stringObjectMap.get("xdwsl").toString());
            wmsPdaQuick.setKcdid(id);
            wmsPdaQuick.setKcid(stringObjectMap.get("kcid").toString());
            wmsPdaQuick.setScrq(stringObjectMap.get("scrq").toString());
            wmsPdaQuick.setSl(stringObjectMap.get("sl").toString());
            wmsPdaQuick.setZdwmc(stringObjectMap.get("zdwmc").toString());
            wmsPdaQuick.setXdwmc(stringObjectMap.get("xdwmc").toString());
            wmsPdaQuick.setKwmc(stringObjectMap.get("kwmc").toString());
            wmsPdaQuick.setCkid(String.valueOf(userinfo.getUser().getOrgId().get(0)));
            List<SysHz> hz=(List<SysHz>)session.getAttribute(BaseSessionInfo.SessionConsignor);
            if(hz.size() > 0){
                wmsPdaQuick.setHzid(hz.get(0).getHzid());
            }
            wmsPdaQuick.setKhmc(wmsQuickExit.getKhmc());
            wmsPdaQuick.setRyid(ryid);
            wmsPdaQuickMapper.baseInsertSelective(wmsPdaQuick);
        }
        //修改快速出库单fyzt 为1
        wmsQuickExit.setBjr(userinfo.getUser().getName());
        wmsQuickExit.setBjsj(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis()));
        dao.updatFyzt1(wmsQuickExit);
        //生成PDA消息推送
        WmsPdaMsg wmsPdaMsg = new WmsPdaMsg();
        wmsPdaMsg.setRyid(ryid);
        wmsPdaMsg.setBt(wmsQuickExit.getFybh());
        wmsPdaMsg.setXx(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis()) + " 下发快速出库任务");
        Integer msgCount = wmsPdaMsgMapper.baseInsertSelective(wmsPdaMsg);
        if(msgCount == 0){
            throw new RuntimeException("生成PDA快速出库任务失败，数据未插入数据库");
        }
        throw new SucessException();
    }

        /**
         * 获取快速出库发运编号
         * @return int
         */
        @BaseServiceDescribe(moduleName = "快速出库", btnName = "获取快速出库发运编号")
        public String getFybh()throws Exception{
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            String fybh = "KC" + df.format(new Date())+Integer.toString((int)(Math.random()*9+1)*1000);
            while (dao.getCountByFybh(fybh) > 0){
                fybh = "KC" + df.format(new Date())+Integer.toString((int)(Math.random()*9+1)*1000);
            }
            return fybh;
        }

     /**
     * 插入一条记录
     * @param entity 实体对象
     * @return int
     */
     @BaseServiceDescribe(moduleName = "快速出库", btnName = "新增快速出库信息")
     @Transactional
    public void baseInsert( WmsQuickExit entity)throws SucessException,ServiceException,Exception{
         if(dao.getCountByFybh(entity.getFybh()) > 0){
             throw new ServiceException("发运编号重复请关闭窗口后重新获取");
         }
         StringBuffer message = new StringBuffer();
         entity.setId(UUIDUtils.uuid());
         entity.setCjsj(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis()));
         entity.setFyzt("0");
         List<WmsQuickExitDetailed> list = new ArrayList<>();
         for (WmsQuickExitDetailed wmsQuickExitDetailed : entity.getWmsQuickExitDetailedList()) {
             //如果库存数量小于要扣减的数量则不允许新增
             if(wmsQuickExitDetailedMapper.getKykcsl(wmsQuickExitDetailed.getHpkcid()) < wmsQuickExitDetailed.getZysl()){
                 Map<String,Object> map =  wmsQuickExitDetailedMapper.getGoodsByKcid(wmsQuickExitDetailed.getHpkcid());
                 message.append("货品名称：" + map.get("hpmc").toString() + " 库位名称："+ map.get("kwmc").toString() + ",");
             }else{
                 wmsQuickExitDetailed.setId(UUIDUtils.uuid());
                 wmsQuickExitDetailed.setKsckid(entity.getId());
                 list.add(wmsQuickExitDetailed);
             }
         }
         wmsQuickExitDetailedMapper.baseInsertAll(list);
         dao.baseInsertSelective( entity );
         throw new SucessException(message.length() > 0 ? message.toString() + "库存不足，扣减失败" : "");
    }

   /**
    * 插入一条记录（匹配有值的字段）
    * @param entity 实体对象
    * @return int
    */
    public Integer baseInsertSelective( WmsQuickExit entity){
         return dao.baseInsertSelective( entity);
    }

   /**
    * 删除（根据主键ID删除）
    * @param id 主键
    * @return int
    */
    public Integer baseDeleteByPrimaryKey( String id){
         return dao.baseDeleteByPrimaryKey( id);
    }

   /**
    * 删除（根据ID 批量删除）
    * @param idList 主键ID列表
    * @return int
    */
    public Integer baseDeleteBathPrimaryKeys( List<String> idList){
         return dao.baseDeleteBathPrimaryKeys( idList );
    }

    /**
    * 分页查询
    * @param entity 实体
    * @return Page<WmsQuickExit>
    */
    public Page<WmsQuickExit> baseSelectPage(WmsQuickExit entity )throws Exception{
        PageHelper.startPage(entity.getPage(),entity.getRows());
        return (Page<WmsQuickExit>)dao.baseSelectPage( entity );
    }

   /**
    * 查询（根据主键ID查询）
    * @param id 主键ID
    * @return WmsQuickExit
    */
    public WmsQuickExit baseSelectByPrimaryKey( String id ){
         return dao.baseSelectByPrimaryKey( id );
    }

   /**
    * 查询（根据ID 批量查询）
    * @param idList 主键ID列表
    * @return list
    */
    public Integer baseSelectBathPrimaryKeys( List<WmsQuickExit> idList ){
         return dao.baseSelectBathPrimaryKeys( idList );
    }

   /**
    *修改 （匹配有值的字段）
    * @param entity 主键ID列表
    * @return int
    */
    public Integer baseUpdateByPrimaryKeySelective( WmsQuickExit entity){
         return dao.baseUpdateByPrimaryKeySelective( entity);
    }

   /**
    *修改（根据主键ID修改）
    * @param entity 主键ID列表
    * @return int
    */
    public Integer baseUpdateByPrimaryKey( WmsQuickExit entity){
         return dao.baseUpdateByPrimaryKey( entity);
    }
}
